﻿using System;
using System.Data.Entity;
using System.Linq;
using MaxStoreErp.Core.BaseClasses;
using Microsoft.Practices.Unity;

namespace MaxStoreShop.Dal
{
    public abstract class RepositoryBase
    {
        [Dependency]
        public ShopContext Context { get; set; }

        protected void SafeDelete<TEntity>(TEntity entity) where TEntity : EntityBase
        {
            entity.IsDeleted = true;
            SaveEntity(entity);
        }

        protected TEntity SaveEntity<TEntity>(TEntity entity) where TEntity : EntityBase
        {
            entity.LastUpdate = DateTime.Now;
            if (entity.IsNew())
            {
                return Create(entity);
            }

            Update(entity);
            return entity;
        }

        T Create<T>(T TObject) where T : EntityBase
        {
            if (TObject == null)
            {
                throw new ArgumentException("Невозможно добавить нулевую сущность.");
            }

            var newEntry = Context.Set<T>().Add(TObject);
            Context.SaveChanges();
            return newEntry;
        }

        void Update<T>(T TObject) where T : EntityBase
        {
            if (TObject == null)
            {
                throw new ArgumentException("Невозможно добавить нулевую сущность.");
            }

            var entry = Context.Entry(TObject);
            if (entry.State == EntityState.Detached)
            {
                var set = Context.Set<T>();
                T attachedEntity = set.Local.SingleOrDefault(e => e.Id == TObject.Id);

                if (attachedEntity != null)
                {
                    var attachedEntry = Context.Entry(attachedEntity);
                    attachedEntry.CurrentValues.SetValues(TObject);
                }
                else
                {
                    entry.State = EntityState.Modified;
                }
            }
            Context.SaveChanges();
        }
    }
}
